﻿using System.Web;
using System.Web.Mvc;
using MvcLibrary.Repository;
using System.IO;
using WebVideo.Areas.Admin.Models;
using System.Linq;
using WebVideo.Controllers;
using System.Collections.Generic;
using CarlosAg.ExcelXmlWriter;
using System;

namespace WebVideo.Areas.Admin.Controllers
{
    public class BusinessController : Controller
    {
        //
        // GET: /Admin/Business/

        public ActionResult Index()
        {

            return View(BusinessModel.Index());
        }

        #region "Insert"
        public ActionResult Insert()
        {
            BusinessModel tnew = new BusinessModel();
            return View(tnew);


        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Insert(BusinessModel Mtnew, HttpPostedFileBase Avatar)
        {

            try
            {
                dbVideoDataContext db = new dbVideoDataContext();
                var query = db.EntityBusinesses.Where(g => g.UserName == Mtnew.UserName);
                var query1 = db.EntityBusinesses.Where(g => g.Email == Mtnew.Email);
                var query3 = db.EntityUsers.Where(g => g.UserName == Mtnew.UserName);
                var query4 = db.EntityUsers.Where(g => g.Email == Mtnew.Email);
                if (query.ToList().Count > 0 || query3.ToList().Count > 0)
                {
                    ModelState.AddModelError("UserName", "UserName đã tồn tại");
                }
                else if (query1.ToList().Count > 0 || query4.ToList().Count > 0)
                {
                    ModelState.AddModelError("Email", "Email đã tồn tại");
                }
                if (ModelState.IsValid)
                {
                    if (Avatar != null && Avatar.ContentLength > 0)
                    {
                        int kb = Avatar.ContentLength / 1024; //file size kb
                        if (kb >= 2048) // file qua lon
                        {
                            return RedirectToAction("Index", "Error", new { errorMsg = "Hình ảnh phải bé hơn 2MB." });
                        }

                        ImageHelper imgHelper = new ImageHelper();
                        string encodestring = imgHelper.encodeImageFile(Avatar);

                        if (encodestring == "!")
                            return RedirectToAction("Index", "Error", new { errorMsg = "Không thể Upload hình" });

                        var path = Path.Combine(Server.MapPath("~/Content/Images/Avatar"), encodestring);
                        Avatar.SaveAs(path);

                        Mtnew.Avatar = encodestring;
                    }
                    BusinessModel.Insert(Mtnew);
                    return RedirectToAction("Index", "Business");
                }
            }
            catch
            {

                return RedirectToAction("Index", "Error", new { errorMsg = "Lỗi SQL hosting / server" });
            }
            return View(Mtnew);
        }
        #endregion //insert

        #region "Edit"
        public ActionResult Edit(string US)
        {
            return View(BusinessModel.LayModel(US));
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(BusinessModel Mtnew,HttpPostedFileBase Avatar)
        {

            try
            {
                if (ModelState.IsValid)
                {
                    if (Avatar != null && Avatar.ContentLength > 0)
                    {
                        int kb = Avatar.ContentLength / 1024; //file size kb
                        if (kb >= 2048) // file qua lon
                        {
                            return RedirectToAction("Index", "Error", new { errorMsg = "Ảnh phải nhỏ hơn 2MB." });
                        }

                        ImageHelper imgHelper = new ImageHelper();
                        string encodestring = imgHelper.encodeImageFile(Avatar);

                        if (encodestring == "!")
                            return RedirectToAction("Index", "Error", new { errorMsg = "Không thể upload ảnh" });

                        var path = Path.Combine(Server.MapPath("~/Content/Images/Avatar"), encodestring);
                        Avatar.SaveAs(path);

                        Mtnew.Avatar = encodestring;
                    }
                    string image = BusinessModel.Edit(Mtnew);
                    if (image != null)
                    {
                        string fileToDelete = Path.Combine(Server.MapPath("~/Content/Images/Avatar"), image); // file hinh cu
                        System.IO.File.Delete(fileToDelete);
                    }
                    return RedirectToAction("Index", "Business");
                }
            }
            catch
            {

                return RedirectToAction("Index", "Error", new { errorMsg = "Lỗi SQL hosting / server" });
            }
            return View(Mtnew);
        }
        #endregion //Edit
        public ActionResult Ban(string US, int l)
        {
            try
            {
                BusinessModel.Ban(US, l);
                return RedirectToAction("Index", "Business");

            }
            catch
            {
                return RedirectToAction("Index", "Error", new { errorMsg = "Lỗi SQL hosting / server" });

            }

        }
        #region "Delete"

        public string Delete(string Username)
        {
            try
            {
                BusinessModel.Delete(Username);
                return "ok";
            }
            catch
            {
                return "error";
            }
        }

        #endregion //Delete

        #region "Xuat bao cao"
        public JsonResult saveExcel()
        {
            Workbook book = new Workbook();
            ReportController rp = new ReportController();
            IList<Report> TieuDe = new List<Report>();
            IList<Report> NoiDung = new List<Report>();
            string Name = "Danh sách Doanh nghiệp";
            dbVideoDataContext db = new dbVideoDataContext();
            // tạo danh sách tiêu đề

            var query = db.EntityBusinesses.ToList();
            

            Report k = new Report();
            k.Name = "UserName";
            TieuDe.Add(k);

            k = new Report();
            k.Name = "Tên công ty";
            TieuDe.Add(k);

            k = new Report();
            k.Name = "Email";
            TieuDe.Add(k);

            k = new Report();
            k.Name = "Tình trạng";
            TieuDe.Add(k);

            k = new Report();
            k.Name = "Địa chỉ";
            TieuDe.Add(k);

            k = new Report();
            k.Name = "Số điện thoại";
            TieuDe.Add(k);

            k = new Report();
            k.Name = "Fax";
            TieuDe.Add(k);

            k = new Report();
            k.Name = "Link Fanpage";
            TieuDe.Add(k);

            k = new Report();
            k.Name = "Địa chỉ website";
            TieuDe.Add(k);

            foreach (var item in query)
            {
                k = new Report();
                k.Name = item.UserName;
                NoiDung.Add(k);

                k = new Report();
                k.Name = item.CompanyName;
                NoiDung.Add(k);

                k = new Report();
                k.Name = item.Email;
                NoiDung.Add(k);

                
                k = new Report();
                if(item.Status == 1)
                     k.Name = "Đang hoạt động";
                else
                    k.Name = "Đang bị ban";
                NoiDung.Add(k);

                k = new Report();
                k.Name = item.Address;
                NoiDung.Add(k);

                k = new Report();
                k.Name = item.PhoneNumber;
                NoiDung.Add(k);

                k = new Report();
                k.Name = item.Fax;
                NoiDung.Add(k);

                k = new Report();
                k.Name = item.LinkFanpage;
                NoiDung.Add(k);

                k = new Report();
                k.Name = item.website;
                NoiDung.Add(k);
            }


            book = rp.Index(book, TieuDe, NoiDung, Name);
            string name = "DoanhNghiep_YeuQuangCao"+ ".xls";
            var path = Path.Combine(Server.MapPath("~/Content/"), name);
            book.Save(path);
            return Json(name);
        }

        #endregion
    }
}
